﻿using B.S.Medical.Api.Write.Application.Command.Department;
using B.S.Medical.Domain.Department;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.Medical.Api.Write.Application.Handler.Department
{
    public class PLDeleteDepartmentCommandHandle : IRequestHandler<PLDeleteDepartmentCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ManageModel> _manageRepository;
        private readonly ILogger<PLDeleteDepartmentCommandHandle> _logger;

        public PLDeleteDepartmentCommandHandle(IBaseRepository<ManageModel> manageRepository, ILogger<PLDeleteDepartmentCommandHandle> logger)
        {
            _manageRepository = manageRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(PLDeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var manages = _manageRepository.GetAll().Where(x => request.Ids.Contains(x.Id) && x.IsDeleted == false).ToList();
            if (manages.Count == 0)
            {
                res.Msg = "未找到要删除的科室!";
                res.Code = ApiEnum.Fail;
                res.Data = 0;
                return res;
            }
            foreach (var manage in manages)
            {
                manage.IsDeleted = true;
                manage.Status = request.Status;
            }
            var r = await _manageRepository.UpdateRangAsync(manages);
            if (r > 0)
            {
                res.Msg = $"批量删除科室成功! 共{r}条";
                res.Code = ApiEnum.Success;
                _logger.LogInformation($"批量删除科室，ID集合: {string.Join(",", request.Ids)} 成功");
                res.Data = r;
            }
            else
            {
                res.Msg = "批量删除科室失败!";
                res.Code = ApiEnum.Fail;
                _logger.LogError($"批量删除科室，ID集合: {string.Join(",", request.Ids)} 失败");
                res.Data = r;
            }
            return res;
        }
    }
}
